<script setup lang="ts">
import type { TableProps } from 'ant-design-vue';

import { computed, onMounted, reactive, ref } from 'vue';

import {
  ArrowRightLeft,
  Download,
  Eye,
  Plus,
  Settings,
  Trash2,
  Upload,
  UserRoundPen,
} from '@vben/icons';

import { message } from 'ant-design-vue';

import BatchSettingsModal from './components/BatchSettingsModal.vue';
import CategoryModal from './components/CategoryModal.vue';
import ImportModal from './components/ImportModal.vue';
import MoveToModal from './components/MoveToModal.vue';
import PackageModal from './components/PackageModal.vue';
// 导入组件
import ProductModal from './components/ProductModal.vue';

// 响应式数据
const activePrimaryCategory = ref('registration');
const selectedCategory = ref('all');
const searchKeyword = ref('');
const categorySearchKeyword = ref('');
const loading = ref(false);

// 模态框控制
const productModalVisible = ref(false);
const packageModalVisible = ref(false);
const categoryModalVisible = ref(false);
const importModalVisible = ref(false);
const batchSettingsModalVisible = ref(false);
const moveToModalVisible = ref(false);

// 当前编辑的商品
const currentProduct = ref<any>(null);

// 选中的行
const selectedRowKeys = ref<string[]>([]);
const selectedRows = ref<any[]>([]);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 表格列定义
const columns: TableProps['columns'] = [
  {
    title: '编号',
    dataIndex: 'code',
    key: 'code',
    width: 120,
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '条形码',
    dataIndex: 'barcode',
    key: 'barcode',
    width: 120,
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    width: 120,
  },
  {
    title: '单位',
    dataIndex: 'unit',
    key: 'unit',
    width: 80,
  },
  {
    title: '有效期',
    dataIndex: 'validityPeriod',
    key: 'validityPeriod',
    width: 100,
  },
  {
    title: '单价',
    dataIndex: 'unitPrice',
    key: 'unitPrice',
    width: 100,
    align: 'right',
    customRender: ({ text }) => `¥${text?.toFixed(2) || '0.00'}`,
  },
  {
    title: '最低售价',
    dataIndex: 'minimumPrice',
    key: 'minimumPrice',
    width: 100,
    align: 'right',
    customRender: ({ text }) => `¥${text?.toFixed(2) || '0.00'}`,
  },
  {
    title: '参与折扣',
    dataIndex: 'participateDiscount',
    key: 'participateDiscount',
    width: 100,
    align: 'center',
  },
  {
    title: '计算库存',
    dataIndex: 'calculateInventory',
    key: 'calculateInventory',
    width: 100,
    align: 'center',
  },
  {
    title: '当前库存',
    dataIndex: 'currentInventory',
    key: 'currentInventory',
    width: 100,
    align: 'right',
    customRender: ({ text }) => text?.toFixed(2) || '0.00',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 模拟数据
const categories = ref([
  { id: 'all', name: '全部', primaryCategory: 'registration' },
  { id: 'outpatient', name: '门诊', primaryCategory: 'registration' },
  { id: 'internal', name: '内科用药', primaryCategory: 'prescription' },
  { id: 'external', name: '外驱', primaryCategory: 'deworming' },
  { id: 'internal-deworming', name: '内驱', primaryCategory: 'deworming' },
  { id: 'package', name: '套餐', primaryCategory: 'deworming' },
]);

const products = ref([
  {
    id: '1',
    code: 'P00000000',
    name: '专家号',
    barcode: '',
    specification: '',
    unit: '次',
    validityPeriod: '',
    unitPrice: 30,
    minimumPrice: 0,
    participateDiscount: false,
    calculateInventory: false,
    currentInventory: 0,
    category: 'outpatient',
    primaryCategory: 'registration',
  },
  {
    id: '2',
    code: 'P00000001',
    name: '普通号',
    barcode: '',
    specification: '',
    unit: '次',
    validityPeriod: '',
    unitPrice: 10,
    minimumPrice: 0,
    participateDiscount: false,
    calculateInventory: false,
    currentInventory: 0,
    category: 'outpatient',
    primaryCategory: 'registration',
  },
  {
    id: '3',
    code: 'P00000002',
    name: '益生菌',
    barcode: '',
    specification: '',
    unit: '盒',
    validityPeriod: '2025-12-31',
    unitPrice: 50,
    minimumPrice: 0,
    participateDiscount: false,
    calculateInventory: false,
    currentInventory: 0,
    category: 'internal',
    primaryCategory: 'prescription',
  },
  {
    id: '4',
    code: 'P00000003',
    name: '健胃消食片',
    barcode: '',
    specification: '',
    unit: '盒',
    validityPeriod: '2025-12-31',
    unitPrice: 20,
    minimumPrice: 0,
    participateDiscount: false,
    calculateInventory: false,
    currentInventory: 0,
    category: 'internal',
    primaryCategory: 'prescription',
  },
]);

// 计算属性
const filteredCategories = computed(() => {
  return categories.value.filter(
    (category) =>
      category.primaryCategory === activePrimaryCategory.value &&
      (categorySearchKeyword.value
        ? category.name.includes(categorySearchKeyword.value)
        : true),
  );
});

const filteredProducts = computed(() => {
  const filtered = products.value.filter(
    (product) =>
      product.primaryCategory === activePrimaryCategory.value &&
      (selectedCategory.value === 'all' ||
        product.category === selectedCategory.value) &&
      (searchKeyword.value
        ? product.name.includes(searchKeyword.value) ||
          product.code.includes(searchKeyword.value) ||
          product.barcode.includes(searchKeyword.value)
        : true),
  );

  // 更新分页总数
  pagination.total = filtered.length;

  return filtered;
});

// 表格行选择配置
const rowSelection = reactive({
  selectedRowKeys,
  onChange: (keys: string[], rows: any[]) => {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
  },
});

// 事件处理函数
const handlePrimaryCategoryChange = (key: string) => {
  activePrimaryCategory.value = key;
  selectedCategory.value = 'all';
  searchKeyword.value = '';
  categorySearchKeyword.value = '';
  selectedRowKeys.value = [];
  selectedRows.value = [];
};

const selectCategory = (categoryId: string) => {
  selectedCategory.value = categoryId;
  selectedRowKeys.value = [];
  selectedRows.value = [];
};

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

const handleCategorySearch = () => {
  // 分类搜索逻辑已在计算属性中处理
};

// 模态框显示函数
const showAddItemModal = () => {
  currentProduct.value = null;
  productModalVisible.value = true;
};

const showAddPackageModal = () => {
  packageModalVisible.value = true;
};

const showAddCategoryModal = () => {
  categoryModalVisible.value = true;
};

const showImportModal = () => {
  importModalVisible.value = true;
};

const showBatchSettingsModal = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要设置的商品');
    return;
  }
  batchSettingsModalVisible.value = true;
};

const showMoveToModal = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要移动的商品');
    return;
  }
  moveToModalVisible.value = true;
};

// 商品操作函数
const editProduct = (product: any) => {
  currentProduct.value = { ...product };
  productModalVisible.value = true;
};

const viewProduct = (product: any) => {
  currentProduct.value = { ...product };
  productModalVisible.value = true;
};

const deleteProduct = async (id: string) => {
  try {
    // 模拟删除请求
    await new Promise((resolve) => setTimeout(resolve, 500));
    products.value = products.value.filter((p) => p.id !== id);
    message.success('删除成功');
  } catch {
    message.error('删除失败');
  }
};

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要删除的商品');
    return;
  }

  try {
    // 模拟批量删除请求
    await new Promise((resolve) => setTimeout(resolve, 500));
    const idsToDelete = new Set(selectedRows.value.map((row) => row.id));
    products.value = products.value.filter((p) => !idsToDelete.has(p.id));
    selectedRowKeys.value = [];
    selectedRows.value = [];
    message.success('批量删除成功');
  } catch {
    message.error('批量删除失败');
  }
};

// 保存处理函数
const handleProductSave = (product: any) => {
  if (product.id) {
    // 编辑现有商品
    const index = products.value.findIndex((p) => p.id === product.id);
    if (index !== -1) {
      products.value[index] = { ...product };
    }
  } else {
    // 添加新商品
    product.id = Date.now().toString();
    product.code = `P${String(products.value.length + 1).padStart(8, '0')}`;
    product.primaryCategory = activePrimaryCategory.value;
    products.value.push(product);
  }
  message.success('保存成功');
  productModalVisible.value = false;
};

const handlePackageSave = (packageData: any) => {
  // 处理套餐保存
  message.success('套餐保存成功');
  packageModalVisible.value = false;
};

const handleCategorySave = (category: any) => {
  if (category.id) {
    // 编辑现有分类
    const index = categories.value.findIndex((c) => c.id === category.id);
    if (index !== -1) {
      categories.value[index] = { ...category };
    }
  } else {
    // 添加新分类
    category.id = Date.now().toString();
    category.primaryCategory = activePrimaryCategory.value;
    categories.value.push(category);
  }
  message.success('分类保存成功');
  categoryModalVisible.value = false;
};

const handleImport = (importData: any) => {
  // 处理导入数据
  message.success('导入成功');
  importModalVisible.value = false;
};

const handleBatchSettings = (settings: any) => {
  // 处理批量设置
  message.success('批量设置成功');
  batchSettingsModalVisible.value = false;
};

const handleMoveTo = (targetCategory: string) => {
  // 处理移动到分类
  selectedRows.value.forEach((row) => {
    const product = products.value.find((p) => p.id === row.id);
    if (product) {
      product.category = targetCategory;
    }
  });
  message.success('移动成功');
  moveToModalVisible.value = false;
  selectedRowKeys.value = [];
  selectedRows.value = [];
};

const handleExport = () => {
  // 处理导出
  message.success('导出成功');
};

// 页面初始化
onMounted(() => {
  // 初始化数据
  loading.value = false;
});
</script>

<template>
  <div class="products-page">
    <!-- 一级分类标签 -->
    <div class="primary-categories">
      <a-tabs
        :active-key="activePrimaryCategory"
        @change="handlePrimaryCategoryChange"
      >
        <a-tab-pane key="registration" tab="挂号" />
        <a-tab-pane key="prescription" tab="处方" />
        <a-tab-pane key="inspection" tab="检验" />
        <a-tab-pane key="imaging" tab="影像" />
        <a-tab-pane key="treatment" tab="处置" />
        <a-tab-pane key="surgery" tab="手术" />
        <a-tab-pane key="inpatient" tab="住院" />
        <a-tab-pane key="boarding" tab="寄养" />
        <a-tab-pane key="vaccine" tab="疫苗" />
        <a-tab-pane key="deworming" tab="驱虫" />
        <a-tab-pane key="beauty" tab="美容" />
        <a-tab-pane key="goods" tab="商品" />
      </a-tabs>
    </div>

    <!-- 操作按钮和搜索区域 -->
    <div class="action-bar">
      <div class="left-actions">
        <a-button type="primary" @click="showAddItemModal">
          <template #icon><Plus /></template>
          添加项目
        </a-button>
        <a-button @click="showAddPackageModal">
          <template #icon><Plus /></template>
          添加套餐
        </a-button>
        <a-button @click="showImportModal">
          <template #icon><Upload /></template>
          导入
        </a-button>
        <a-button @click="handleExport">
          <template #icon><Download /></template>
          导出
        </a-button>
        <a-button @click="showBatchSettingsModal">
          <template #icon><Settings /></template>
          批量设置
        </a-button>
        <a-button @click="showMoveToModal">
          <template #icon><ArrowRightLeft /></template>
          移动到
        </a-button>
        <a-button danger @click="handleBatchDelete">
          <template #icon><Trash2 /></template>
          删除
        </a-button>
      </div>
      <div class="search-area">
        <a-input-search
          :value="searchKeyword"
          @update:value="searchKeyword = $event"
          placeholder="名称/编码/条形码"
          style="width: 300px"
          @search="handleSearch"
        />
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧分类筛选 -->
      <div class="category-sidebar">
        <div class="category-header">
          <span class="category-title">分类</span>
          <a-button type="link" size="small" @click="showAddCategoryModal">
            <template #icon><Plus /></template>
            添加分类
          </a-button>
        </div>
        <div class="category-search">
          <a-input
            :value="categorySearchKeyword"
            @update:value="categorySearchKeyword = $event"
            placeholder="名称"
            size="small"
            @change="handleCategorySearch"
          />
        </div>
        <div class="category-list">
          <div
            v-for="category in filteredCategories"
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            {{ category.name }}
          </div>
        </div>
      </div>

      <!-- 右侧商品列表 -->
      <div class="products-content">
        <a-table
          :columns="columns"
          :data-source="filteredProducts"
          :row-selection="rowSelection"
          :pagination="pagination"
          :loading="loading"
          row-key="id"
          size="middle"
        >
          <!-- 参与折扣列 -->
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'participateDiscount'">
              <a-tag :color="record.participateDiscount ? 'green' : 'red'">
                {{ record.participateDiscount ? '是' : '否' }}
              </a-tag>
            </template>
            <!-- 计算库存列 -->
            <template v-else-if="column.key === 'calculateInventory'">
              <a-tag :color="record.calculateInventory ? 'green' : 'red'">
                {{ record.calculateInventory ? '是' : '否' }}
              </a-tag>
            </template>
            <!-- 操作列 -->
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="editProduct(record)">
                  <template #icon><UserRoundPen /></template>
                  编辑
                </a-button>
                <a-button type="link" size="small" @click="viewProduct(record)">
                  <template #icon><Search /></template>
                  查看
                </a-button>
                <a-popconfirm
                  title="确定要删除这个商品吗？"
                  @confirm="deleteProduct(record.id)"
                >
                  <a-button type="link" size="small" danger>
                    <template #icon><Trash2 /></template>
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 添加/编辑商品模态框 -->
    <ProductModal
      v-model:visible="productModalVisible"
      :product="currentProduct"
      :primary-category="activePrimaryCategory"
      @save="handleProductSave"
    />

    <!-- 添加套餐模态框 -->
    <PackageModal
      v-model:visible="packageModalVisible"
      :primary-category="activePrimaryCategory"
      @save="handlePackageSave"
    />

    <!-- 添加分类模态框 -->
    <CategoryModal
      v-model:visible="categoryModalVisible"
      :primary-category="activePrimaryCategory"
      @save="handleCategorySave"
    />

    <!-- 导入模态框 -->
    <ImportModal
      v-model:visible="importModalVisible"
      :primary-category="activePrimaryCategory"
      @import="handleImport"
    />

    <!-- 批量设置模态框 -->
    <BatchSettingsModal
      v-model:visible="batchSettingsModalVisible"
      :selected-rows="selectedRows"
      @save="handleBatchSettings"
    />

    <!-- 移动到模态框 -->
    <MoveToModal
      v-model:visible="moveToModalVisible"
      :selected-rows="selectedRows"
      :categories="categories"
      @move="handleMoveTo"
    />
  </div>
</template>

<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .left-actions {
    justify-content: center;
  }

  .main-content {
    flex-direction: column;
  }

  .category-sidebar {
    width: 100%;
    height: 200px;
  }
}

.products-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.primary-categories {
  padding: 0 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.action-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.left-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.category-sidebar {
  display: flex;
  flex-direction: column;
  width: 250px;
  background: white;
  border-right: 1px solid #e8e8e8;
}

.category-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.category-title {
  font-weight: 600;
  color: #333;
}

.category-search {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.category-list {
  flex: 1;
  overflow-y: auto;
}

.category-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.category-item:hover {
  background-color: #f5f5f5;
}

.category-item.active {
  color: #1890ff;
  background-color: #e6f7ff;
  border-right: 3px solid #1890ff;
}

.products-content {
  display: flex;
  flex: 1;
  flex-direction: column;
  overflow: hidden;
}

.products-content :deep(.ant-table-wrapper) {
  flex: 1;
  overflow: hidden;
}

.products-content :deep(.ant-table) {
  height: 100%;
}

.products-content :deep(.ant-table-container) {
  height: 100%;
}

.products-content :deep(.ant-table-body) {
  overflow-y: auto;
}
</style>
